package middleware

import (
	"log"
	"writerhelper/global"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

type MyClaims struct {
	jwt.StandardClaims
	Email string
}

func ParseJwt() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		log.Println(token)

		parseToken, err := jwt.ParseWithClaims(token, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
			return global.MySigningKey, nil
		})
		// log.Println(parseToken.Valid)
		// 当服务器重启的时候，jwt会过期，需要重新登录
		if !parseToken.Valid {
			//err 储存的是过期信息，提示多长时间之前过期 注意测试的时候要对应账户明码
			c.JSON(200, gin.H{
				"code":    "代码待定，token出错",
				"message": "token is wrong",
				"err":     err.Error(),
			})
			c.Abort()
		}
		if claims, ok := parseToken.Claims.(*MyClaims); ok {
			c.Set("email", claims.Email)
		}
	

	}
}
